<template>
    <div>
        <h1>多轮对话</h1>
        <div v-for="(msg, index) in messages" :key="index"
            :class="{ 'user-message': msg.role === 'user', 'assistant-message': msg.role === 'assistant' }">
            <strong>{{ msg.role === 'user' ? '您:' : '店员:' }}</strong> {{ msg.content }}
        </div>
        <input v-model="userInput" @keyup.enter="sendMessage" placeholder="请输入您的问题">
        <button @click="sendMessage">发送</button>
    </div>
</template>

<script>
import OpenAI from "openai";

export default {
    name: '多轮对话',
    data() {
        return {
            messages: [
                {
                    role: "system",
                    content: `你是一名百炼手机商店的店员，你负责给用户推荐手机。手机有两个参数：屏幕尺寸（包括6.1英寸、6.5英寸、6.7英寸）、分辨率（包括2K、4K）。
            你一次只能向用户提问一个参数。如果用户提供的信息不全，你需要反问他，让他提供没有提供的参数。如果参数收集完成，你要说：我已了解您的购买意向，请稍等。`,
                },
                {
                    role: "assistant",
                    content: "欢迎光临百炼手机商店，您需要购买什么尺寸的手机呢？",
                },
            ],
            userInput: "",
        };
    },
    methods: {
        async sendMessage() {
            if (this.userInput.trim() === "") return;

            this.messages.push({ role: "user", content: this.userInput });
            this.userInput = "";

            try {
                const response = await this.getResponse(this.messages);
                this.messages.push({ role: "assistant", content: response });
            } catch (error) {
                console.error("获取响应时发生错误:", error);
            }
        },
        async getResponse(messages) {
            const openai = new OpenAI({
                apiKey: process.env.VUE_APP_DASHSCOPE_API_KEY,
                baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
                dangerouslyAllowBrowser: true
            });

            try {
                const completion = await openai.chat.completions.create({
                    model: "qwen-plus",
                    messages: messages,
                });
                return completion.choices[0].message.content;
            } catch (error) {
                console.error("获取响应时发生错误:", error);
                throw error;
            }
        },
    },
};
</script>

<style scoped>
.user-message {
    margin-bottom: 10px;
    color: blue;
}

.assistant-message {
    margin-bottom: 10px;
    color: green;
}
</style>